import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'subject.dart';

class EventListener extends StatefulWidget {
  const EventListener({super.key});

  @override
  State<EventListener> createState() => _EventListenerState();
}

class _EventListenerState extends State<EventListener> {
  String? loggedInUser;
  late final StreamSubscription subscription;

  @override
  void initState() {
    super.initState();

    // 监听事件：当 UserLoggedInEvent 被触发时，回调此函数
    subscription = eventBus.on<UserLoggedInEvent>().listen((event) {
      setState(() {
        loggedInUser = event.userName;
      });
      if (kDebugMode) {
        print('收到登录事件，用户：${event.userName}');
      }
    });
  }

  @override
  void dispose() {
    subscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Center(
          child: loggedInUser == null
              ? Text(
                  '等待用户登录事件...',
                  style: TextStyle(fontSize: 16, color: Colors.grey),
                )
              : Text(
                  '🎉 欢迎回来，$loggedInUser！您已登录',
                  style: TextStyle(fontSize: 18, color: Colors.green),
                ),
        ),
      ),
    );
  }
}
